package org.ligson.spark.util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

public class HttpUtil {
    private static CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    private static CloseableHttpResponse doRequest(HttpRequestBase requestBase) {
        try {
            return httpClient.execute(requestBase);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static CloseableHttpResponse doGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        return doRequest(httpGet);
    }

    public static String doGetText(String url) {
        CloseableHttpResponse response = doGet(url);
        try {
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
